<template>
  <ul>
    <!--
      因为默认情况下路由切换之后，组件会被销毁
      所以这里的输入框输入一些文字后，切到Message后再切回来，这些输入都会消失
      如果想要缓存组件，让组件不被销毁，需要在父组件Home中设置keep-alive标签
      -->
    <li :style="{opacity}">欢迎学习Vue</li>
    <li>news001<input type="text"></li>
    <li>news002<input type="text"></li>
    <li>news003<input type="text"></li>
  </ul>
</template>

<script>
export default {
  name: "News",
  data() {
    return {
      opacity: 1,
    }
  },
  beforeDestroy() {
    //如果组件被设置了keep-alive，切走时组件不会销毁，定时器依然持续执行，造成代码效率降低
    console.log('New组件即将被销毁')
    //clearInterval(this.timer)
  },
  mounted() {
    console.log('New组件挂载完毕')
    // this.timer = setInterval(()=>{
    //   console.log('timer is running')  
    //   this.opacity -= 0.01
    //   if (this.opacity <= 0) {
    //     this.opacity = 1
    //   }
    // }, 16)
  },
  /*
  两个路由组件独有的生命周期函数，activated（路由被激活）和deactived（路由失活）
  可以代替mounted和beforeDestroy，对于被keep-alive的路由组件依然生效
  */
  activated() {
    console.log('New组件被激活')
    this.timer = setInterval(()=>{
      console.log('timer is running') 
      this.opacity -= 0.01
      if (this.opacity <= 0) {
        this.opacity = 1
      }
    }, 16)
  },
  deactivated() {
    console.log('New组件失活')
    clearInterval(this.timer)
  }
}
</script>

<style scoped>

</style>
